package com.soecode.wxtools.util.http;

import com.alibaba.fastjson.JSONObject;
import com.soecode.wxtools.bean.result.WxError;
import com.soecode.wxtools.exception.WxErrorException;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;

public interface RequestExecutor<T, E> {

	T execute(CloseableHttpClient httpclient, String uri, E data)
			throws WxErrorException,  IOException;

	default  String validate(CloseableHttpClient httpclient,HttpUriRequest request) throws WxErrorException, IOException {
        try (CloseableHttpResponse response = httpclient.execute(request)) {
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            JSONObject node = JSONObject.parseObject(responseContent);
            if(node.get("errcode")!=null && !(node.getIntValue("errcode")==0)){
                WxError error = WxError.fromJson(responseContent);
                throw new WxErrorException(error);
            }
            return responseContent;
        }
    }

}
